class EventEmitter {
  constructor() {
    this._events_ = Object.create(null);
  }
}

EventEmitter.prototype.on = function (type, callback) {
  if (this._events_[type]) {
    this._events_[type].push(callback);
  } else {
    this._events_[type] = [callback];
  }
};

EventEmitter.prototype.emit = function (type, ...args) {
  if (this._events_[type]) {
    this._events_[type].forEach(function (cb) {
      cb.call(this, ...args);
    });
  }
};

EventEmitter.prototype.off = function (type, callback) {
  if (this._events_[type]) {
    this._events_[type] = this._events_[type].filter(
      (cb) => cb !== callback && cb.link !== callback
    );
  }
};

EventEmitter.prototype.once = function (type, callback) {
  // 注册callback并执行一次，之后销毁
  const _this = this;
  function once(...args) {
    callback.call(this, ...args);
    _this.off(type, once);
  }
  // 将工具函数与真正的cb建立联系，用于适应在once之后立即off的场景
  once.link = callback;
  this.on(type, once);
};

let e = new EventEmitter();
const fn = function (...args) {
  console.log("111", args);
};
e.once("event1", fn);
// e.on("event1", (...args) => {
//   console.log("2212", args);
// });
e.off("event1", fn);
e.emit("event1", 1, 2);
// e.off("event1", fn);
e.emit("event1", 3, 4);
